<template>
  <div class="shopping-container">
    <!-- 黑色遮罩 -->
    <div :class="showShoppingCart ? 'open-black-mask' : 'black-mask'" @click="closeMask"></div>

    <!-- 购物车列表 -->
    <div :class="showShoppingCart ? 'open-shopping-content' : 'shopping-content'" ref="moveCartModule">
      <div class="clear-btn" ref="showClearBtn">
        <a class="clearGoods" href="javascript:;" @click="clearOrder">{{ $t('m.goods.clear') }}</a>
      </div>
      <div class="order-module">
        <div class="order-info" v-for="item in nowOrderList" :key="item.id">
          <van-card :price="item.discount_amount > 0 ? item.price - item.discount_amount + '.00':item.price +'.00'"
            :tag="item.discount_amount > 0?'折扣':''" :title="item.name" :currency="$t('m.goods.money')"
            :thumb="item.image_thumbnail_cdn===''||item.image_thumbnail_cdn===null?localIMG:item.image_thumbnail_cdn">
            <template #tags>
              <span class="discount-amount" v-if="item.discount_amount > 0">￥{{item.price}}</span>
            </template>
            <template #footer>
              <div class="count-btn">
                <van-button size="mini" @click="subAmount(item.id)">━</van-button>
                <span class="amount">{{ item.amount }}</span>
                <van-button size="mini" @click="addAmount(item.id)">╋</van-button>
              </div>
            </template>
          </van-card>
        </div>
      </div>
    </div>

    <!-- 支付统计栏 -->
    <div :class="detailsStatus?'move-pay-module':'pay-module'">
      <div class="cart-box" @click="openOrder">
        <div class="review">
          <div :class="showShoppingCart ? 'iconfont open-jiantou' : 'iconfont close-jiantou'"></div>
          <span>{{ $t('m.goods.review') }}</span>
        </div>
        <div class="iconfont iconcart">
          <span class="amount">{{ 'X' + amount }}</span>
        </div>
      </div>
      <div class="pay-box" @click="ToPay" ref="payBox">
        <span class="pay-icon">{{ $t('m.goods.pay') }}</span>
        <div class="price">
          <span>{{ $t('m.goods.money') }}</span>
          <span>{{ expensesList.totalSum }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import bus from '@/eventBus.js'

export default {
  props: ['nowOrderList', 'detailsStatus', 'shopConfig', 'shopsInfo'],
  data() {
    return {
      // 控制清单滑入滑出
      showShoppingCart: false,
      amount: 0,
      // 收费清单
      expensesList: {
        discountSum: 0, // 折扣金额
        serviceRate: 0, // 服务费率
        serviceSum: 0, // 服务费总计
        preTaxSum: 0, // 税前总计
        taxRate: 0, // 税率
        taxSum: 0, // 税额总计
        totalSum: 0, // 税后总计
        deliverySum: 0, // 派送费
        FinalTotalSum: 0 // 最终合计
      },
      // 购物车列表详情(商品列表，收费列表)
      listDetails: {},
      minAmount: this.shopsInfo.config.min_order_amount,
      localIMG: './../static/img/mxbc/Ice_Cream/Ferris_Crispy.jpeg'
    }
  },
  watch: {
    // 监听订单列表对象属性数值变化
    nowOrderList: {
      handler(newVal) {
        // // 当购物车数据变化时自动显示购物车、支付组件
        // setTimeout(() => {
        //   this.showShoppingCart = true
        // }, 30)
        // 商品数量为0自动删除当前对象
        setTimeout(() => {
          newVal.find((o, i) => {
            if (o.amount === 0) {
              this.nowOrderList.splice(i, 1)
              return true
            }
          })
        }, 90)
        this.countAmounts()
        this.countSum()
        // 商品详情页, 购物车为 0 时不显示清单列表 box
        if (newVal.length === 0) {
          this.$refs.moveCartModule.style.display = 'none'
          this.showShoppingCart = false
        } else {
          this.$refs.moveCartModule.style.display = 'block'
        }
      },
      deep: true
    },
    // 监听父传子 =>GoodsPage 改变支付栏、清单box 位置
    detailsStatus() {
      if (this.detailsStatus) {
        this.$refs.moveCartModule.style.zIndex = 1
        this.$refs.moveCartModule.style.bottom = '3em'
      } else {
        this.$refs.moveCartModule.style.zIndex = 0
        this.$refs.moveCartModule.style.bottom = '6em'
      }
    },
    // 监听收费清单是否满足最低消费额, 满足则支付栏变色
    expensesList: {
      handler(list) {
        if (list.totalSum > this.minAmount) {
          this.$refs.payBox.style.background = 'orange'
        } else {
          this.$refs.payBox.style.background = ''
        }
      },
      deep: true
    }
  },
  // 初始化清单数量和总金额
  created() {
    this.countAmounts()
    this.countSum()
    // 兄传兄 =>GoodsInfo 控制清单列表隐藏
    bus.$on('closeList', val => {
      this.showShoppingCart = val
    })
  },
  methods: {
    // 点击遮罩区域隐藏购物车
    closeMask() {
      this.openOrder()
    },
    // 购物车显示、隐藏
    openOrder() {
      if (this.nowOrderList.length === 0) {
        this.$notify({ type: 'warning', message: '请先加入商品', duration: 1500 })
      } else {
        this.showShoppingCart = !this.showShoppingCart
      }
    },
    // 清除所有订单
    clearOrder() {
      this.nowOrderList.forEach((item, i) => {
        this.nowOrderList[i].amount = 0
      })
    },
    // 计算总数量
    countAmounts() {
      this.amount = 0
      this.nowOrderList.forEach(item => {
        this.amount += item.amount
      })
    },
    // 计算总金额、服务费、税费、优惠
    countSum() {
      this.expensesList.totalSum = 0
      this.expensesList.discountSum = 0
      var num = 0
      this.nowOrderList.forEach(item => {
        if (item.discount_amount > 0 || this.shopConfig.tax || this.shopConfig.service_charge) {
          num += (item.price - item.discount_amount) * item.amount
          // 优惠总额
          this.expensesList.discountSum += item.discount_amount * item.amount
          // 税总额
          this.expensesList.taxSum = Math.round(num * (this.shopConfig.tax_rate * 0.01) * 100) / 100
          // 服务费总额
          this.expensesList.serviceSum = Math.round(num * (this.shopConfig.service_charge_rate * 0.01) * 100) / 100
        } else {
          num += item.price * item.amount
        }
        // 默认只计算含税价格
        this.expensesList.totalSum = Math.round((num + this.expensesList.taxSum) * 100) / 100
        // 不含税价格
        this.expensesList.preTaxSum = Math.round(num * 100) / 100
        // 存储税率
        this.expensesList.taxRate = this.shopConfig.tax_rate * 0.01
        // 存储服务费率
        this.expensesList.serviceRate = this.shopConfig.service_charge_rate * 0.01
      })
    },
    // 减去数量
    subAmount(id) {
      this.nowOrderList.some((item, i) => {
        if (item.id === id) {
          if (this.nowOrderList[i].amount > 0) {
            this.nowOrderList[i].amount--
          }
          return true
        }
      })
    },
    // 增加数量
    addAmount(id) {
      this.nowOrderList.some((item, i) => {
        if (item.id === id) {
          if (this.nowOrderList[i].amount < 10) {
            this.nowOrderList[i].amount++
          }
          return true
        }
      })
    },
    // 判断总价是否满足最低消费额, 满足则可跳转支付
    ToPay() {
      if (this.expensesList.totalSum < this.minAmount) {
        this.$notify({ type: 'warning', message: '最低消费' + this.minAmount + '元', duration: 1500 })
      } else {
        this.listDetails.goodsList = this.nowOrderList
        this.listDetails.expensesList = this.expensesList
        this.listDetails.shopsInfo = this.shopsInfo
        // 通过 vuex 传输列表详情到 提交订单 组件
        this.$store.commit('submitGoodsList', this.listDetails)
        // 此状态用于管理从 Address 组件返回时的路由路径 和 是否显示 Payments支付组件
        this.$store.commit('changeIsForOrder', true)
        this.$router.push('/home/view')
      }
    }
  }
}
</script>

<style lang="less">
.open-black-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background: black;
  opacity: 0.3;
  display: block;
}
.open-shopping-content {
  position: absolute;
  width: 100%;
  bottom: 6em;
  background: white;
  border-top-left-radius: 9px;
  border-top-right-radius: 9px;
  transition: all 0.3s;
  transform: translateY(0);
  box-shadow: 0px 11px 15px 0px black;
}
.open-jiantou:before {
  content: '\e892';
  margin-right: 0.5em;
  font-size: 0.5em;
}
.move-pay-module {
  display: flex;
  position: absolute;
  width: 100%;
  height: 3em;
  background: #f7f7f7;
  bottom: 0;
  z-index: 1;
  transition: all 0.3s;
}

.black-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background: black;
  opacity: 0.3;
  display: none;
}
.pay-module {
  display: flex;
  position: absolute;
  width: 100%;
  height: 3em;
  background: #f7f7f7;
  bottom: 50px;
  z-index: 1;
  transition: all 0.3s;
}
.cart-box {
  display: flex;
  align-items: center;
  width: 50%;
  .review {
    display: flex;
    width: 40%;
    margin-left: 1.5em;
    text-align: center;
    color: #636363;
    font-size: 0.9em;
    .close-jiantou:before {
      content: '\e87e';
      margin-right: 0.5em;
      font-size: 0.5em;
    }
  }
  .iconcart:before {
    content: '\e613';
    font-size: 1.5em;
    padding-right: 0.3em;
  }
  .amount {
    font-size: 0.9em;
    color: #696969;
  }
}
.pay-box {
  display: flex;
  flex-direction: column;
  width: 50%;
  background: #c9c9c9;
  .pay-icon {
    display: flex;
    align-items: center;
    margin-left: 0.9em;
    font-size: 0.6em;
    color: white;
  }
  .price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 0.3em;
    margin-right: 0.3em;
    font-size: 1.55em;
    color: #545454;
  }
}
.shopping-content {
  position: absolute;
  width: 100%;
  bottom: 6em;
  transition: all 0.3s;
  transform: translateY(150%);
  box-shadow: 0px 11px 15px 0px black;
}
.clear-btn {
  position: relative;
  width: 100%;
  height: 36px;
  border-top-left-radius: 9px;
  border-top-right-radius: 9px;
  background: #fafafa;
  .clearGoods {
    line-height: 36px;
    margin-left: 1em;
    font-size: 0.9em;
    color: #a3a3a3;
  }
}
.order-module {
  width: 100%;
  max-height: 240px;
  overflow: auto;
  .order-info {
    float: left;
    width: 100%;
    height: 80px;
    .van-card {
      display: flex;
      align-items: center;
      height: 100%;
      line-height: 80px;
      .van-image {
        display: flex;
        justify-content: center;
        .van-image__img {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          width: 60px;
          height: 60px;
        }
      }
      .van-card__title {
        position: relative;
        top: 21px;
        height: 1.2em;
        font-size: 1.2em;
        line-height: 1.2em;
      }
      .van-card__price {
        position: relative;
        bottom: 12px;
        color: red;
        .van-card__price-currency {
          font-size: 1.4em;
        }
      }
      .van-card__footer {
        position: absolute;
        right: 20px;
        .count-btn {
          display: flex;
          align-items: center;
          .amount {
            font-size: 1.3em;
            color: #696969;
          }
          .van-button:nth-child(1) {
            width: 21px;
            height: 21px;
            border-radius: 50%;
            margin-right: 10px;
            color: black;
            border: 1px solid black;
          }
          .van-button:nth-child(3) {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            margin-left: 10px;
            color: white;
            background: orange;
            border: 1px solid orange;
          }
        }
      }
      .van-tag--mark {
        transform: translate(30%, -130%) scale(0.8);
      }
    }
  }
  .discount-amount {
    position: absolute;
    top: 0.5em;
    margin-left: 0.1em;
    color: #b8b8b8;
    font-size: 1.2em;
    text-decoration: line-through;
  }
}
</style>
